package portal.servicios;

import java.util.Properties;

import javax.ejb.Stateless;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;

import org.jboss.logging.Logger;

import portal.entidades.MonitoreoLog;
import portal.util.xml.LogXml;
import portal.util.xml.XmlUtil;

@Stateless
public class InformarAsincronicoBean implements InformarAsincronico {

 	private ConnectionFactory connectionFactory;
 	private Queue queue;
 	private static Logger logger = Logger.getLogger(InformarAsincronicoBean.class);

    public InformarAsincronicoBean() {
        
    }

	@Override
	public void informarLog(MonitoreoLog log, String conexion, String cola) {
		
		try {
			logger.info(" ####### InformarLOG Start #######");
			Properties env = new Properties();
			env.setProperty(InitialContext.INITIAL_CONTEXT_FACTORY,"org.jboss.naming.remote.client.InitialContextFactory");
			env.setProperty(InitialContext.PROVIDER_URL, conexion);//remote://192.168.0.205:24447
			Context ctx = new InitialContext(env);
			connectionFactory = (ConnectionFactory) ctx.lookup("jms/RemoteConnectionFactory");
			queue = (Queue) ctx.lookup(cola);//jms/queue/portal
			
			Connection connection = connectionFactory.createConnection();
			Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
			TextMessage message = session.createTextMessage();
			MessageProducer producer = session.createProducer(queue);
			// Armo Xml
			String xml = XmlUtil.monitoreoLog2Xml(log);
			message.setText(xml);
			producer.send(message);
			// Cierro Conexiones
			producer.close();
			connection.close();
			logger.info("Log informado OK");
			
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("Se encontrarion problemas al informarLOG, ERROR: "  + e.getMessage());
		}
		
		logger.info(" ####### InformarLOG END #######");
		
	}

}
